package session

import (
	"time"
	"sync"
	"video_server/api/defs"
	"video_server/api/dbops"
	"video_server/api/utils"
	"log"
)



// 线程安全的map，缓存session信息
var sessionMap *sync.Map

func init() {
	sessionMap = &sync.Map{}
}

func nowInMilli() int64 {
	return time.Now().UnixNano() / 1e6
}

func deleteExpiredSession(sid string) {
	sessionMap.Delete(sid)
	dbops.DeleteSession(sid)
}

func LoadSessionFromDB() {
	sessions, err := dbops.RetrieveAllSessions()
	if err != nil {
		log.Printf("Error: %s", err)
		return
	}
	sessions.Range(func(key, value interface{}) bool {
		ss := value.(*defs.SimpleSession)
		sessionMap.Store(key, ss)
		return true
	})
}

func GenerateNewSessionId(username string) string { 
	sessionID, _ := utils.NewUUID()
	ct := time.Now().UnixNano() / 1e6;
	ttl := ct + 30*60*1000 // 30分钟有效期

	ss := &defs.SimpleSession{Username: username, TTL: ttl / 1000}
	sessionMap.Store(sessionID, ss)
	dbops.SaveSessionToDB(sessionID, ttl, username)
	return sessionID
}

func IsSessionExpired(sid string) (string, bool) {
	session, ok := sessionMap.Load(sid)
	if !ok {
		return "", true
	}
	ct := time.Now().UnixNano() / 1e6
	if session.(*defs.SimpleSession).TTL < ct {
		deleteExpiredSession(sid)
		return "", true
	}
	return session.(*defs.SimpleSession).Username, false
}


